import React, { memo, useEffect, useState, useRef, useMemo, useCallback } from 'react';
import TableList from './c-cpns/TableList';
import FormModal from './c-cpns/FormModal';
import { Button, message } from 'antd';
import { insertItem, editItemById, delItemByIdArray } from '@/utils/list';
import { getTableDataList } from '@/api/archives/practice';

import classNames from 'classnames/bind';
import style from './style/style.module.scss';
const cx = classNames.bind(style);

const Practice = memo(() => {
  console.log('+++++++++++++++++++++++');
  const [tableData, setTableData] = useState([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [payload, setPayload] = useState({
    pageNo: 1,
    pageSize: 5,
    param: { businessType: 1, receiveType: 1 }
  });

  // 查询table数据
  const queryTableData = async () => {
    setLoading(true);
    const { data } = await getTableDataList(payload);
    setLoading(false);
    setTableData(data.results);
    setTotal(data.totalCount);
  };

  useEffect(() => {
    queryTableData();
  }, [payload]);

  const formModalRef = useRef<{ setOpen: any }>();
  const activeEditDataRef = useRef<any>();

  // 新增
  const showFormModal = () => {
    activeEditDataRef.current = {};
    formModalRef.current.setOpen(true);
  };
  // 新增成功
  const onAddSuccess = (data: any) => {
    setTableData((preValue): any => {
      const newData = insertItem(data, preValue);
      return newData;
    });
    message.success('提交成功');
    formModalRef.current.setOpen(false);
  };
  // 编辑
  const editItem = useCallback((data: any) => {
    activeEditDataRef.current = data;
    formModalRef.current.setOpen(true);
  }, []);
  // 编辑成功
  const onEditSuccess = useCallback((data: any) => {
    // console.log('编辑成功后的结果：', data);
    const newData = editItemById(data.id, data, tableData);
    setTableData(newData);
    message.success('编辑成功');
    formModalRef.current.setOpen(false);
  }, []);

  const onPageChange = useCallback((page: number) => {
    setPayload({ ...payload, pageNo: page });
  }, []);

  return (
    <>
      <div className={cx('tool')}>
        <div className={cx('title')}>table标题</div>
        <div className={cx('toolbars')}>
          <Button type="primary" onClick={showFormModal}>
            新建
          </Button>
        </div>
      </div>
      <TableList
        loading={loading}
        data={tableData}
        total={total}
        editItem={editItem}
        onPage={onPageChange}
      />
      {useMemo(
        () => (
          <FormModal
            ref={formModalRef}
            formData={activeEditDataRef}
            onAdd={onAddSuccess}
            onEdit={onEditSuccess}
          />
        ),
        []
      )}
    </>
  );
});

export default Practice;
